package com.caihao.onenote.controller;


import com.caihao.onenote.constant.JwtClaimsConstant;
import com.caihao.onenote.dto.Result;
import com.caihao.onenote.dto.UserDTO;
import com.caihao.onenote.entity.User;
import com.caihao.onenote.properties.JwtProperties;
import com.caihao.onenote.service.UserService;
import com.caihao.onenote.utils.JwtUtil;
import com.caihao.onenote.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService  userService;
    @Autowired
    private JwtProperties jwtProperties;


    //用户登录接口
    @GetMapping("/hello")
    public String hello(){
        return "helloWorld,你爹的项目已成功上线";
    }

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserDTO userDTO) throws AccountLockedException, AccountNotFoundException {
        /*// 实现登录功能
        return userService.login(loginForm, session);*/

        log.info("员工登录：{}", userDTO);

        User user = userService.login(userDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        //构建返回对象信息
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
}
